package web

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"iris_blog/utils"
)

type Article struct {
}

// 首页的分页列表
func (a Article) GetAll(i iris.Context) {

	// page 当前页
	page, _ := i.URLParamInt("page")
	if page == -1 || page == 0 {
		page = 1
	}
	// pageSize 每页条数
	pageSize, _ := i.URLParamInt("pageSize")
	if pageSize == -1 {
		pageSize = 5
	}

	// 总条数
	var count int
	utils.DB.Raw("select count(*) from article").Find(&count)

	fmt.Println(page, pageSize, count, "==========")
	results := []map[string]interface{}{}
	utils.DB.Debug().Raw("SELECT * FROM article ORDER BY add_time DESC  LIMIT ? OFFSET ? ", pageSize, (page-1)*pageSize).Find(&results)

	i.JSON(map[string]interface{}{
		"code": 20000,
		"data": results,
		"page": map[string]interface{}{
			"count":    count,
			"pageSize": pageSize,
			"page":     page,
		},
	})
}

// 通过路由号  获取文章参数
func (a Article) GetObjectId(i iris.Context) {
	id, err := i.Params().GetInt("id")
	if err != nil {
		i.WriteString("非法请求")
		return
	}
	fmt.Println(id)

	results := []map[string]interface{}{}
	utils.DB.Raw("SELECT * FROM article WHERE id = ?", id).Find(&results)

	i.JSON(map[string]interface{}{
		"code": 20000,
		"data": results,
	})
}

// 获取前10条数据
func (a Article) GetTen(i iris.Context) {

	results := []map[string]interface{}{}
	utils.DB.Raw("select * from article ORDER BY add_time DESC limit ?", 9).Find(&results)

	i.JSON(map[string]interface{}{
		"code": 20000,
		"data": results,
	})

}
